package com.xzzz.irda.tracker.client;

import cn.hutool.core.util.StrUtil;
import com.xzzz.common.base.util.json.JsonUtil;
import com.xzzz.common.base.util.okhttp.HttpUtil;
import com.xzzz.irda.tracker.core.SpanNode;
import com.xzzz.irda.tracker.core.TrackerProperties;
import com.xzzz.irda.tracker.core.repository.TrackerRepository;
import com.xzzz.irda.tracker.core.common.TrackerConstants;
import lombok.extern.slf4j.Slf4j;

import java.util.List;

/**
 * 客户端远程持久化, 客户端采用远程持久化的方式, 将 span 信息发送到远程 server 端, 由服务端实现具体的持久化方法。
 */
@Slf4j
public class TrackerHttpRemoteServerRepository implements TrackerRepository {

    private final TrackerProperties.Http httpProperties;

    private final String remoteHost;

    /**
     * 客户端
     *
     * @param trackerCollectorProperties 客户端收集器
     */
    public TrackerHttpRemoteServerRepository(TrackerProperties properties) {
        log.info("[TRACKERS] 开启追踪信息发送HTTP到服务端持久化");
        this.httpProperties = properties.getRepository().getHttp();
        remoteHost = httpProperties.getHttpUrl() + TrackerConstants.API.SERVER_SAVE_SPAN;
        if (StrUtil.isBlank(remoteHost)) {
            log.warn("[TRACKERS] 开启追踪信息发送HTTP到服务端持久化[失败], 未配置服务器地址[remoteHost]");
        }
    }

    @Override
    public boolean save(List<SpanNode> spanNodes) {
        if (StrUtil.isBlank(remoteHost)) {
            return false;
        }
        try {
            HttpUtil.post(remoteHost, JsonUtil.toJson(spanNodes));
            return true;
        } catch (Exception e) {
            log.warn("[TRACKERS] SPAN 信息持久化失败: {}", e.getMessage());
            return false;
        }
    }
}
